package com.ruoyi.system.interceptor;


import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.interceptor.Interceptor;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Forest.AuthToken;
import com.ruoyi.system.service.QueryTokenClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class TokenHeaderInterceptor implements Interceptor<Object> {

    @Resource
    private QueryTokenClient authClient;

    @Autowired
    private RedisCache redisCache;

    @Override
    public boolean beforeExecute(ForestRequest request) {

        String token = redisCache.getCacheObject(CacheConstants.IOT_TOKEN);
        if (token == null) {
            AuthToken authToken = authClient.authToken();
            if (authToken != null){
                token = authToken.getAccess_token();
                redisCache.setCacheObject(CacheConstants.IOT_TOKEN,  token, authToken.getExpires_in()- 60 * 60, TimeUnit.SECONDS);

            }else {
                return false;
            }

        }
        if (StringUtils.isNotEmpty(token)){
            request.addHeader("Authorization", "Bearer " + token);
            return true;
        }
        return false;
    }
}
